<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="gain-key-container">
      <!-- 顶部开关区域 -->
      <div class="switch-area">
        <!-- 自来水总闸开关 -->
        <div class="switch-title">总控开关</div>
        <div class="switch-group">
          <div class="switch-item">
            <span class="switch-label">自来水总闸:</span>
            <i-switch
              v-model="waterMainSwitch.value"
              @on-change="handleMainSwitchChange('waterMainSwitch')"
              size="large"
            >
              <span slot="open">开</span>
              <span slot="close">关</span>
            </i-switch>
          </div>
          <div class="switch-item">
            <span class="switch-label">压缩空气总闸开关:</span>
            <i-switch
              v-model="airMainSwitch.value"
              @on-change="handleMainSwitchChange('airMainSwitch')"
              size="large"
            >
              <span slot="open">开</span>
              <span slot="close">关</span>
            </i-switch>
          </div>
          <div class="switch-item">
            <span class="switch-label">蒸汽回水切换闸开关:</span>
            <i-switch
              v-model="steamSwitch.value"
              @on-change="handleMainSwitchChange('steamSwitch')"
              size="large"
            >
              <span slot="open">开</span>
              <span slot="close">关</span>
            </i-switch>
          </div>
        </div>
        <!-- 其他开关 -->
      </div>

      <!-- 主体四象限布局 -->
      <Row :gutter="16" class="middle-area">
        <Col span="12">
          <!-- 加药槽补水表格 -->
          <div class="quadrant-title">加药槽补水</div>
          <vxe-table
            :data="chemicalTanks"
            border
            class="table"
            height="320px"
            show-overflow
            :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
          >
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column field="name" title="参数名称"></vxe-column>
            <vxe-column
              field="upAlarmLimit.value"
              title="报警上限"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.upAlarmLimit.value"
                  type="number"
                  :min="0"
                  :max="2"
                  :step="0.01"
                  @blur="handleBlur(row, 'upAlarmLimit', 'chemicalTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="setUpperLimit.value"
              title="设定上限"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.setUpperLimit.value"
                  type="number"
                  :min="0"
                  :max="2"
                  :step="0.01"
                  @blur="handleBlur(row, 'setUpperLimit', 'chemicalTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="setLowerLimit.value"
              title="设定下限"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.setLowerLimit.value"
                  type="number"
                  :min="0"
                  :max="2"
                  :step="0.01"
                  @blur="handleBlur(row, 'setLowerLimit', 'chemicalTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="lowAlarmLimit.value"
              title="报警下限"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.lowAlarmLimit.value"
                  type="number"
                  :min="0"
                  :max="2"
                  :step="0.01"
                  @blur="handleBlur(row, 'lowAlarmLimit', 'chemicalTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column field="actualValue.value" title="实际液位"></vxe-column>
            <vxe-column field="autoSwitch.value" title="自动开关">
              <template #default="{ row }">
                <i-switch
                  v-model="row.autoSwitch.value"
                  size="large"
                  @on-change="
                    handleSwitchChange(
                      row,
                      'autoSwitch',
                      'chemicalTanks',
                      row.autoSwitch.value
                    )
                  "
                >
                  <span slot="open">手动</span>
                  <span slot="close">自动</span>
                </i-switch>
              </template>
            </vxe-column>
            <vxe-column field="waterStatus.value" title="补水状态">
              <template #default="{ row }">
                <Button
                  :type="row.waterStatus.value ? 'success' : 'error'"
                  :disabled="!row.autoSwitch.value"
                  @click="
                    handleStatusChange(row, 'waterStatus', 'chemicalTanks')
                  "
                >
                  {{ row.waterStatus.value ? '运行中' : '停止中' }}
                </Button>
              </template>
            </vxe-column>
            <vxe-column field="alarmStatus.value" title="报警状态">
              <template #default="{ row }">
                <Tag
                  v-if="row.alarmStatus.value"
                  class="alarm-status"
                  color="error"
                >
                  液位报警
                </Tag>
              </template>
            </vxe-column>
          </vxe-table>
        </Col>
        <Col span="12">
          <!-- PH添加表格 -->
          <div class="quadrant-title">槽体加药设定</div>
          <vxe-table
            class="table"
            :data="dosingTanks"
            height="320px"
            border
            show-overflow
            :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
          >
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column field="name" title="参数名称"></vxe-column>
            <vxe-column
              field="setCount.value"
              title="设定挂数"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.setCount.value"
                  type="number"
                  :min="0"
                  :max="30000"
                  :step="1"
                  @blur="handleBlur(row, 'setCount', 'dosingTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="totalCount.value"
              title="累计挂数"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.totalCount.value"
                  type="number"
                  :min="0"
                  :max="30000"
                  :step="1"
                  @blur="handleBlur(row, 'totalCount', 'dosingTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="runSetTime.value"
              title="运行设时"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.runSetTime.value"
                  type="number"
                  :min="0"
                  :max="30000"
                  :step="1"
                  @blur="handleBlur(row, 'runSetTime', 'dosingTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column
              field="runTimer.value"
              title="运行计时"
              :edit-render="{}"
            >
              <template #edit="{ row }">
                <vxe-input
                  v-model="row.runTimer.value"
                  type="number"
                  :min="0"
                  :max="30000"
                  :step="1"
                  @blur="handleBlur(row, 'runTimer', 'dosingTanks')"
                />
              </template>
            </vxe-column>
            <vxe-column field="autoSwitch.value" title="自动开关">
              <template #default="{ row }">
                <i-switch
                  v-model="row.autoSwitch.value"
                  size="large"
                  @on-change="
                    handleSwitchChange(
                      row,
                      'autoSwitch',
                      'dosingTanks',
                      row.autoSwitch.value
                    )
                  "
                >
                  <span slot="open">手动</span>
                  <span slot="close">自动</span>
                </i-switch>
              </template>
            </vxe-column>
            <vxe-column field="dosingStatus.value" title="添加状态">
              <template #default="{ row }">
                <Button
                  :type="row.dosingStatus.value ? 'success' : 'error'"
                  :disabled="!row.autoSwitch.value"
                  @click="
                    handleStatusChange(row, 'dosingStatus', 'dosingTanks')
                  "
                >
                  {{ row.dosingStatus.value ? '开启中' : '停止中' }}
                </Button>
              </template>
            </vxe-column>
          </vxe-table>
        </Col>
      </Row>
      <Row :gutter="16" class="footer-area">
        <Col span="12">
          <!-- 水槽补水表格 -->
          <div class="quadrant-title">水槽补水</div>
          <vxe-table
            :data="waterTanks"
            border
            show-overflow
            height="300px"
            class="table"
          >
            <vxe-column type="seq" width="60"></vxe-column>
            <vxe-column field="name" title="参数名称"></vxe-column>
            <vxe-column field="levelStatus.value" title="液位状态">
              <template #default="{ row }">
                <Tag :color="row.levelStatus.value ? 'success' : 'error'">
                  {{ row.levelStatus.value ? '高' : '低' }}
                </Tag>
              </template>
            </vxe-column>
            <vxe-column field="autoSwitch.value" title="自动开关">
              <template #default="{ row }">
                <i-switch
                  v-model="row.autoSwitch.value"
                  size="large"
                  @on-change="
                    handleSwitchChange(
                      row,
                      'autoSwitch',
                      'waterTanks',
                      row.autoSwitch.value
                    )
                  "
                >
                  <span slot="open">手动</span>
                  <span slot="close">自动</span>
                </i-switch>
              </template>
            </vxe-column>
            <vxe-column field="waterStatus.value" title="补水状态">
              <template #default="{ row }">
                <Button
                  :type="row.waterStatus.value ? 'success' : 'error'"
                  :disabled="!row.autoSwitch.value"
                  @click="handleStatusChange(row, 'waterStatus', 'waterTanks')"
                >
                  {{ row.waterStatus.value ? '运行中' : '停止中' }}
                </Button>
              </template>
            </vxe-column>
          </vxe-table>
        </Col>
      </Row>
    </div>
  </div>
</template>

<script lang="ts">
import {
  I_cmd,
  T_cmd,
  T_srv,
  Tsrv,
  airMainSwitch,
  chemicalTanks,
  ifs,
  steamSwitch,
  ts,
  tvs,
  vue,
  waterMainSwitch,
  waterTanks,
  DosingTanks,
  N_AddHydrationSettings
} from './config';

@T_srv.comp
export default class cAddHydrationSettings extends vue {
  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private name: string = 'cAddHydrationSettings';

  private funName: string = 'cAddHydrationSettings';

  private G_compName: string = this.name;

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  private isMask: boolean = false;

  // 响应式数据
  public waterMainSwitch: N_AddHydrationSettings.SwitchState = waterMainSwitch();

  public airMainSwitch: N_AddHydrationSettings.SwitchState = airMainSwitch();

  public steamSwitch: N_AddHydrationSettings.SwitchState = steamSwitch();

  public chemicalTanks: N_AddHydrationSettings.ChemicalTank[] = chemicalTanks();

  public waterTanks: N_AddHydrationSettings.WaterTank[] = waterTanks();

  public dosingTanks: N_AddHydrationSettings.DosingTank[] = DosingTanks();

  public ecDetCodes: string[] = [];

  created() {
    // 如果父组件没有传参，那就产生一个
    this.GT_compBoxInfo = Tsrv.getCompInfo(this.compBoxInfo);
    this.G_compID = this.GT_compBoxInfo.compID;
    this.GT_compBox = this.GT_compBoxInfo.TcompBox;
    this.GT_command.init(this, this.GT_compBoxInfo);
    this.init();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_command.startTask();
    this.receiveEvent();
  }

  destroyed() {
    this.GT_command.stopTask();
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);
    this.$bus.$off('__PLC_CONNSTATE__');

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  private receiveEvent() {
    this.$bus.$on(
      '__PLC_CONNSTATE__',
      (data: { connState: boolean; ecBoxName: string }) => {
        if (data.ecBoxName === 'mianyang') {
          if (data.connState) {
            if (!this.GT_command.isOpenTask) {
              this.GT_command.startTask();
            }
          } else {
            this.GT_command.stopTask();
          }
        }
      }
    );
  }

  private init() {
    // 获取所有点位
    const codes = [
      this.waterMainSwitch.code,
      this.airMainSwitch.code,
      this.steamSwitch.code
    ];
    this.chemicalTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name') {
          codes.push(item[key].code);
        }
      });
    });

    this.waterTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name' && key !== 'levelStatus') {
          codes.push(item[key].code);
        }
      });
    });

    this.dosingTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name') {
          codes.push(item[key].code);
        }
      });
    });

    this.ecDetCodes = codes;
  }

  public updateData(res: any) {
    this.waterMainSwitch.value = !res[this.waterMainSwitch.code].v;
    this.airMainSwitch.value = res[this.airMainSwitch.code].v;
    this.steamSwitch.value = res[this.steamSwitch.code].v;
    this.chemicalTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name' && key !== '_XID') {
          item[key].value = res[item[key].code].v;
        }
      });
    });

    this.waterTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name' && key !== '_XID') {
          if (key === 'levelStatus') {
            // 根据高低液位计算显示状态
            const isHigh = res[item.hignLevel.code].v;
            const isLow = res[item.lowLevel.code].v;
            item.levelStatus.value = isHigh ? true : isLow ? false : null;
          } else {
            item[key].value = res[item[key].code].v;
          }
        }
      });
    });

    this.dosingTanks.forEach(item => {
      Object.keys(item).forEach(key => {
        if (key !== 'name' && key !== '_XID') {
          item[key].value = res[item[key].code].v;
        }
      });
    });
  }

  private handleSwitchChange(
    row: any,
    field: string,
    param: string,
    value: boolean
  ) {
    const d = [{ ecDetCode: row[field].code, value: value.toString() }];
    Tsrv.writePlcData(d).then(_ => {
      // 读取数据
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this[param].forEach(item => {
            if (item.name === row.name) {
              item[field].value = res[row[field].code].v;
            }
          });
        }
      });
    });
  }

  private handleMainSwitchChange(param: string) {
    const d = [
      {
        ecDetCode: this[param].code,
        value:
          param === 'waterMainSwitch'
            ? (!this[param].value).toString()
            : this[param].value.toString()
      }
    ];
    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([this[param].code]).then(res => {
        if (typeof res !== 'boolean') {
          this[param].value = res[this[param].code].v;
        }
      });
    });
  }

  private handleStatusChange(row: any, field: string, param: string) {
    if (row.autoSwitch.value) return;

    const newValue = !row[field].value;
    const d = [{ ecDetCode: row[field].code, value: newValue.toString() }];

    Tsrv.writePlcData(d).then(_ => {
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this[param].forEach(item => {
            if (item.name === row.name) {
              item[field].value = res[row[field].code].v;
            }
          });
        }
      });
    });
  }

  // 失焦事件处理
  public handleBlur(row: any, field: string, param: string) {
    const originalValue = row[field].value;
    const newValue = row[field].value;
    // if (originalValue !== newValue) {
    // 调用接口更新
    // this.updateParameter(row[field].code, newValue);

    const d = [{ ecDetCode: row[field].code, value: newValue.toString() }];
    Tsrv.writePlcData(d).then(_ => {
      // 读取数据
      Tsrv.readPlcData([row[field].code]).then(res => {
        if (typeof res !== 'boolean') {
          this[param].forEach(item => {
            if (item.name === row.name) {
              item[field].value = res[row[field].code].v;
            }
          });
        }
      });
    });
  }
}
</script>

<style lang="scss" scoped>
.gain-key-container {
  padding: 16px;
  height: calc(100vh - 32px);
  display: flex;
  flex-direction: column;

  .switch-area {
    margin-bottom: 16px;
    padding: 12px;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    .switch-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 12px;
      color: #606266;
    }

    .switch-group {
      display: flex;
      // gap: 24px;
      justify-content: space-between;

      .switch-item {
        display: flex;
        // flex-direction: column;
        gap: 8px;
        align-items: center;

        .switch-label {
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }

  .quadrant-title {
    font-size: 16px;
    font-weight: bold;
    padding: 8px 12px;
    background: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px 4px 0 0;
    margin-bottom: -1px;
  }

  .quadrant-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: #fff;
    overflow: hidden;

    .quadrant-content {
      flex: 1;
      padding: 12px;
      overflow: auto;
    }
  }

  .table {
    height: calc(100% - 50px);
  }

  .grid-form {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    height: 100%;
  }

  .middle-area {
    height: 42%;
    background-color: #fff;
    margin-bottom: 10px;
  }

  .footer-area {
    height: 42%;
    background-color: #fff;
  }
}

@keyframes alarm-blink {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
  100% {
    opacity: 1;
  }
}

.alarm-status {
  animation: alarm-blink 1s ease-in-out infinite;
}
</style>
